// BoLe HR Platform - 认证和用户管理

class AuthManager {
    constructor() {
        this.currentUser = null;
        this.init();
    }

    init() {
        // 从localStorage恢复用户信息
        const savedUser = localStorage.getItem('user');
        if (savedUser) {
            this.currentUser = JSON.parse(savedUser);
        }

        // 检查认证状态
        this.checkAuthStatus();
        
        // 绑定表单事件
        this.bindEvents();
    }

    bindEvents() {
        // 登录表单
        const loginForm = document.getElementById('loginForm');
        if (loginForm) {
            loginForm.addEventListener('submit', (e) => this.handleLogin(e));
        }

        // 注册表单
        const registerForm = document.getElementById('registerForm');
        if (registerForm) {
            registerForm.addEventListener('submit', (e) => this.handleRegister(e));
        }

        // 用户类型选择
        const userTypeSelect = document.getElementById('userType');
        if (userTypeSelect) {
            userTypeSelect.addEventListener('change', (e) => this.handleUserTypeChange(e));
        }

        // 候选人档案表单
        const candidateProfileForm = document.getElementById('candidateProfileForm');
        if (candidateProfileForm) {
            candidateProfileForm.addEventListener('submit', (e) => this.handleCandidateProfile(e));
        }
    }

    async checkAuthStatus() {
        // 检查是否为测试模式（localhost环境或演示环境）
        if (window.location.hostname === 'localhost' || 
            window.location.hostname === '127.0.0.1' || 
            window.location.hostname.includes('10.112.140.137')) {
            this.enableTestMode();
            return;
        }
        
        const token = localStorage.getItem('access_token');
        if (token) {
            try {
                // 验证token是否有效
                const user = await api.getCurrentUser();
                this.currentUser = user;
                localStorage.setItem('user', JSON.stringify(user));
                this.showDashboard();
            } catch (error) {
                console.error('Token validation failed:', error);
                this.logout();
            }
        } else {
            // 如果没有token，也启用测试模式
            this.enableTestMode();
        }
    }

    enableTestMode() {
        console.log('🧪 启用测试模式 - 自动登录');
        
        // 创建测试用户
        this.currentUser = {
            id: 'test_user_001',
            username: 'Demo HR',
            email: 'hr@demo.com',
            user_type: 'hr', // 默认为HR用户
            is_test: true,
            is_demo: true
        };
        
        // 保存到localStorage (同步多种key以兼容不同系统)
        localStorage.setItem('user', JSON.stringify(this.currentUser));
        localStorage.setItem('currentUser', JSON.stringify(this.currentUser));
        localStorage.setItem('access_token', 'test_token_123');
        localStorage.setItem('authToken', 'test_token_123');
        
        this.showDashboard();
        this.showTestModeNotification();
    }

    showTestModeNotification() {
        // 显示测试模式通知
        const notification = document.createElement('div');
        notification.id = 'test-mode-notification';
        notification.innerHTML = `
            <div style="
                position: fixed; 
                top: 10px; 
                right: 10px; 
                background: #ff9800; 
                color: white; 
                padding: 10px 15px; 
                border-radius: 5px; 
                z-index: 10000;
                font-size: 14px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            ">
                🧪 测试模式 | 当前: ${this.currentUser.user_type === 'hr' ? 'HR' : '求职者'}
                <button onclick="authManager.switchTestUserType()" style="
                    background: rgba(255,255,255,0.2); 
                    border: none; 
                    color: white; 
                    padding: 2px 8px; 
                    border-radius: 3px; 
                    cursor: pointer; 
                    margin-left: 5px;
                ">切换</button>
                <button onclick="this.parentElement.parentElement.remove()" style="
                    background: none; 
                    border: none; 
                    color: white; 
                    margin-left: 5px; 
                    cursor: pointer;
                ">×</button>
            </div>
        `;
        document.body.appendChild(notification);
    }

    switchTestUserType() {
        if (this.currentUser && this.currentUser.is_test) {
            // 切换用户类型
            this.currentUser.user_type = this.currentUser.user_type === 'hr' ? 'candidate' : 'hr';
            localStorage.setItem('user', JSON.stringify(this.currentUser));
            
            // 更新UI
            this.showDashboard();
            
            // 更新通知
            const notification = document.getElementById('test-mode-notification');
            if (notification) {
                notification.remove();
                this.showTestModeNotification();
            }
            
            // 显示切换提示
            if (window.showToast) {
                window.showToast(`已切换到${this.currentUser.user_type === 'hr' ? 'HR' : '求职者'}模式`);
            }
        }
    }

    async handleLogin(event) {
        event.preventDefault();
        
        const form = event.target;
        const formData = new FormData(form);
        const credentials = {
            username: formData.get('username'),
            password: formData.get('password')
        };

        // 验证表单
        if (!validateForm(form)) {
            showToast('请填写所有必填字段', 'error');
            return;
        }

        try {
            // 显示加载状态
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 登录中...';
            submitBtn.disabled = true;

            // 调用登录API
            const response = await api.login(credentials);
            
            this.currentUser = response.user;
            showToast('登录成功！', 'success');
            
            // 显示对应的仪表板
            this.showDashboard();

        } catch (error) {
            console.error('Login failed:', error);
            showToast(error.message || '登录失败，请检查用户名和密码', 'error');
        } finally {
            // 恢复按钮状态
            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.innerHTML = '<i class="fas fa-sign-in-alt"></i> 登录';
            submitBtn.disabled = false;
        }
    }

    async handleRegister(event) {
        event.preventDefault();
        
        const form = event.target;
        const formData = new FormData(form);
        const userData = {
            email: formData.get('email'),
            username: formData.get('username'),
            password: formData.get('password'),
            user_type: formData.get('user_type'),
            company_name: formData.get('company_name') || null
        };

        // 验证表单
        if (!validateForm(form)) {
            showToast('请填写所有必填字段', 'error');
            return;
        }

        // 验证密码强度
        if (userData.password.length < 6) {
            showToast('密码长度至少6位', 'error');
            return;
        }

        try {
            // 显示加载状态
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 注册中...';
            submitBtn.disabled = true;

            // 调用注册API
            const response = await api.register(userData);
            
            showToast('注册成功！请登录', 'success');
            
            // 切换到登录页面
            showSection('login');
            
            // 预填用户名
            document.getElementById('loginUsername').value = userData.username;

        } catch (error) {
            console.error('Registration failed:', error);
            showToast(error.message || '注册失败，请稍后重试', 'error');
        } finally {
            // 恢复按钮状态
            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.innerHTML = '<i class="fas fa-user-plus"></i> 注册';
            submitBtn.disabled = false;
        }
    }

    handleUserTypeChange(event) {
        const userType = event.target.value;
        const companyGroup = document.getElementById('companyGroup');
        
        if (userType === 'hr') {
            companyGroup.style.display = 'block';
            document.getElementById('companyName').required = true;
        } else {
            companyGroup.style.display = 'none';
            document.getElementById('companyName').required = false;
        }
    }

    async handleCandidateProfile(event) {
        event.preventDefault();
        
        const form = event.target;
        const formData = new FormData(form);
        
        // 处理技能标签
        const skillsString = formData.get('skills');
        const skills = skillsString ? skillsString.split(',').map(s => s.trim()).filter(s => s) : [];
        
        const profileData = {
            full_name: formData.get('full_name'),
            phone: formData.get('phone'),
            location: formData.get('location'),
            current_position: formData.get('current_position'),
            experience_years: parseInt(formData.get('experience_years')) || 0,
            skills: skills,
            github_url: formData.get('github_url'),
            linkedin_url: formData.get('linkedin_url'),
            portfolio_url: formData.get('portfolio_url')
        };

        try {
            // 显示加载状态
            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
            submitBtn.disabled = true;

            // 调用API
            const response = await api.createOrUpdateProfile(profileData);
            
            showToast('档案保存成功！', 'success');

        } catch (error) {
            console.error('Profile update failed:', error);
            showToast(error.message || '档案保存失败，请稍后重试', 'error');
        } finally {
            // 恢复按钮状态
            const submitBtn = form.querySelector('button[type="submit"]');
            submitBtn.innerHTML = '<i class="fas fa-save"></i> 保存档案';
            submitBtn.disabled = false;
        }
    }

    showDashboard() {
        if (!this.currentUser) {
            showSection('login');
            return;
        }

        // 更新导航栏
        this.updateNavbar();

        // 根据用户类型显示对应仪表板
        if (this.currentUser.user_type === 'hr') {
            showSection('hr-dashboard');
            document.getElementById('hrUserName').textContent = this.currentUser.username;
            // 初始化HR仪表板
            if (window.hrManager) {
                hrManager.init();
            }
        } else if (this.currentUser.user_type === 'candidate') {
            showSection('candidate-dashboard');
            document.getElementById('candidateUserName').textContent = this.currentUser.username;
            // 初始化求职者仪表板
            if (window.candidateManager) {
                candidateManager.init();
            }
        }
    }

    updateNavbar() {
        const navMenu = document.getElementById('navMenu');
        if (this.currentUser) {
            // 用户已登录，显示用户菜单
            navMenu.innerHTML = `
                <span class="nav-link">欢迎，${this.currentUser.username}</span>
                <a href="#" class="nav-link" onclick="authManager.logout()">
                    <i class="fas fa-sign-out-alt"></i> 退出
                </a>
            `;
        } else {
            // 用户未登录，显示默认菜单
            navMenu.innerHTML = `
                <a href="#" class="nav-link" onclick="showSection('home')">首页</a>
                <a href="#" class="nav-link" onclick="showSection('login')">登录</a>
                <a href="#" class="nav-link" onclick="showSection('register')">注册</a>
            `;
        }
    }

    logout() {
        // 清除认证信息
        api.clearToken();
        this.currentUser = null;
        
        // 更新界面
        this.updateNavbar();
        showSection('home');
        
        showToast('已安全退出', 'info');
    }

    isAuthenticated() {
        return !!this.currentUser;
    }

    isHR() {
        return this.currentUser && this.currentUser.user_type === 'hr';
    }

    isCandidate() {
        return this.currentUser && this.currentUser.user_type === 'candidate';
    }

    requireAuth() {
        // 演示模式强制通过认证
        if (window.location.hostname === 'localhost' || 
            window.location.hostname === '127.0.0.1' || 
            window.location.hostname.includes('10.112.140.137') ||
            window.location.port === '3000') {
            if (!this.isAuthenticated()) {
                this.enableTestMode();
            }
            return true;
        }
        
        if (!this.isAuthenticated()) {
            showToast('请先登录', 'warning');
            showSection('login');
            return false;
        }
        return true;
    }

    requireHR() {
        // 演示模式强制通过HR认证
        if (window.location.hostname === 'localhost' || 
            window.location.hostname === '127.0.0.1' || 
            window.location.hostname.includes('10.112.140.137') ||
            window.location.port === '3000') {
            if (!this.isAuthenticated()) {
                this.enableTestMode();
            }
            if (!this.isHR()) {
                // 演示模式下强制设为HR用户
                this.currentUser.user_type = 'hr';
                localStorage.setItem('user', JSON.stringify(this.currentUser));
            }
            return true;
        }
        
        if (!this.requireAuth()) return false;
        if (!this.isHR()) {
            showToast('只有HR用户可以访问此功能', 'error');
            return false;
        }
        return true;
    }

    requireCandidate() {
        if (!this.requireAuth()) return false;
        if (!this.isCandidate()) {
            showToast('只有求职者可以访问此功能', 'error');
            return false;
        }
        return true;
    }
}

// 全局函数
function logout() {
    authManager.logout();
}

function editProfile() {
    const form = document.getElementById('candidateProfileForm');
    const inputs = form.querySelectorAll('input, select, textarea');
    
    inputs.forEach(input => {
        input.disabled = false;
    });
    
    // 滚动到表单顶部
    form.scrollIntoView({ behavior: 'smooth' });
}

// 创建全局认证管理器实例
const authManager = new AuthManager();